import { useState, useEffect } from "react";
import styles from "./PendingOrdersQuery.module.css";

interface PendingOrder {
    id: number;
    warehouse: string;
    team: string;
    inventoryCode: string;
    states: string;
}

interface QueryParams {
    warehouse: string;
    team: string;
    inventoryCode: string;
}

interface AddFormData {
    warehouse: string;
    team: string;
    inventoryCode: string;
    states: string;
}

const PendingOrdersQuery = () => {
    // 定义数组对象，用于存储API返回的数据
    const [pendingorderList, setPendingorderList] = useState<PendingOrder[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    // 添加选中项的状态
    const [selectedItems, setSelectedItems] = useState<number[]>([]);
    
    // 下拉框选项
    const [warehouseOptions, setWarehouseOptions] = useState<{ value: string; label: string; }[]>([
        { value: '仓库1', label: '仓库1' },
        { value: '仓库2', label: '仓库2' },
        { value: '仓库3', label: '仓库3' },
    ]);
    const [teamOptions, setTeamOptions] = useState<{ value: string; label: string; }[]>([
        { value: '团队1', label: '团队1' },
        { value: '团队2', label: '团队2' },
        { value: '团队3', label: '团队3' },
    ]);
    
    // 查询条件状态
    const [queryParams, setQueryParams] = useState<QueryParams>({
        warehouse: '',
        team: '',
        inventoryCode: ''
    });

    // 弹出框状态
    const [showModal, setShowModal] = useState(false);
    const [showEditModal, setShowEditModal] = useState(false);
    const [saving, setSaving] = useState(false);
    const [loading2, setLoading2] = useState(false);
    const [currentEditId, setCurrentEditId] = useState<number | null>(null);
    const [formData, setFormData] = useState<AddFormData>({
        warehouse: '',
        team: '',
        inventoryCode: '',
        states: '启用'
    });
    const [editFormData, setEditFormData] = useState<AddFormData>({
        warehouse: '',
        team: '',
        inventoryCode: '',
        states: '启用'
    });

    // 生成盘点单号
    const generateInventoryCode = () => {
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const time = String(now.getHours()).padStart(2, '0') + String(now.getMinutes()).padStart(2, '0') + String(now.getSeconds()).padStart(2, '0');
        return `PD${year}${month}${day}${time}`;
    };

    // 获取待盘点订单数据
    const fetchPendingOrders = async (params?: QueryParams) => {
        try {
            setLoading(true);
            setError(null);
            
            // 构建查询URL
            let url = 'http://localhost:5233/api/PendingOrders/QueryPendingOrders';
            const queryString = new URLSearchParams();
            
            if (params) {
                if (params.warehouse.trim()) {
                    queryString.append('Warehouse', params.warehouse.trim());
                }
                if (params.team.trim()) {
                    queryString.append('Team', params.team.trim());
                }
                if (params.inventoryCode.trim()) {
                    queryString.append('InventoryCode', params.inventoryCode.trim());
                }
            }
            
            if (queryString.toString()) {
                url += '?' + queryString.toString();
            }
            
            console.log('请求URL:', url); // 调试信息
            
            const response = await fetch(url);
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const data = await response.json();
            console.log('API返回数据:', data); // 调试信息
            
            // 处理不同的数据格式
            let processedData: PendingOrder[] = [];
            
            if (Array.isArray(data)) {
                // 直接是数组
                processedData = data;
            } else if (data && typeof data === 'object') {
                // 检查常见的包装格式
                if (Array.isArray(data.data)) {
                    processedData = data.data;
                } else if (Array.isArray(data.result)) {
                    processedData = data.result;
                } else if (Array.isArray(data.list)) {
                    processedData = data.list;
                } else if (Array.isArray(data.items)) {
                    processedData = data.items;
                } else {
                    console.error('未知的数据格式:', data);
                    throw new Error('API返回的数据格式不正确');
                }
            } else {
                throw new Error('API返回的数据不是有效格式');
            }
            
            setPendingorderList(processedData);
        } catch (err) {
            setError(err instanceof Error ? err.message : '获取数据失败');
            console.error('获取待盘点订单失败:', err);
        } finally {
            setLoading(false);
        }
    };

    // 组件挂载时获取数据
    useEffect(() => {
        fetchPendingOrders();
    }, []);

    // 处理查询参数变化
    const handleInputChange = (field: keyof QueryParams, value: string) => {
        setQueryParams(prev => ({
            ...prev,
            [field]: value
        }));
    };

    // 执行查询
    const handleSearch = () => {
        fetchPendingOrders(queryParams);
    };

    // 清空查询条件
    const handleClear = () => {
        const emptyParams = { warehouse: '', team: '', inventoryCode: '' };
        setQueryParams(emptyParams);
        fetchPendingOrders();
    };

    // 打开新增弹出框
    const handleAdd = () => {
        setFormData({
            warehouse: '',
            team: '',
            inventoryCode: generateInventoryCode(),
            states: '启用'
        });
        setShowModal(true);
    };

    // 关闭弹出框
    const handleCloseModal = () => {
        setShowModal(false);
        setFormData({
            warehouse: '',
            team: '',
            inventoryCode: '',
            states: '启用'
        });
    };

    // 处理表单输入变化
    const handleFormChange = (field: keyof AddFormData, value: string) => {
        setFormData(prev => ({
            ...prev,
            [field]: value
        }));
    };

    // 保存新增数据
    const handleSave = async () => {
        if (!formData.warehouse.trim() || !formData.team.trim()) {
            alert('请填写完整的仓库和团队信息');
            return;
        }

        try {
            setSaving(true);
            const response = await fetch('http://localhost:5233/api/PendingOrders/AddPendingOrders', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    Warehouse: formData.warehouse.trim(),
                    Team: formData.team.trim(),
                    InventoryCode: formData.inventoryCode,
                    States: formData.states
                })
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();
            console.log('新增成功:', result);
            
            // 关闭弹出框并重新加载数据
            handleCloseModal();
            fetchPendingOrders(queryParams);
            alert('新增成功！');
        } catch (err) {
            console.error('新增失败:', err);
            alert('新增失败: ' + (err instanceof Error ? err.message : '未知错误'));
        } finally {
            setSaving(false);
        }
    };

    // 打开编辑弹出框
    const handleEdit = async (id: number) => {
        setCurrentEditId(id);
        setLoading2(true);
        
        // 先从当前列表中获取数据进行预填充
        const currentItem = pendingorderList.find(item => item.id === id);
        if (currentItem) {
            setEditFormData({
                warehouse: currentItem.warehouse,
                team: currentItem.team,
                inventoryCode: currentItem.inventoryCode,
                states: currentItem.states
            });
        }
        
        setShowEditModal(true);
        
        try {
            // 调用API获取最新数据
            const response = await fetch(`http://localhost:5233/api/PendingOrders/FindPendingOrders?Id=${id}`);
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const result = await response.json();
            console.log('API返回数据:', result);
            
            // 根据你提供的数据格式处理
            if (result && result.code === 200 && result.data) {
                let editData = null;
                
                if (Array.isArray(result.data) && result.data.length > 0) {
                    // 如果data是数组，取第一个元素
                    editData = result.data[0];
                } else if (result.data && typeof result.data === 'object') {
                    // 如果data是对象，直接使用
                    editData = result.data;
                }
                
                if (editData) {
                    // 更新表单数据
                    setEditFormData({
                        warehouse: editData.warehouse || '',
                        team: editData.team || '',
                        inventoryCode: editData.inventoryCode || '',
                        states: editData.states || '启用'
                    });
                    console.log('成功设置编辑数据:', editData);
                } else {
                    console.log('未找到有效的编辑数据');
                }
            } else {
                console.log('API返回格式不正确:', result);
            }
            
        } catch (err) {
            console.error('获取编辑数据失败:', err);
            // 如果API调用失败，使用列表中的数据继续编辑
        } finally {
            setLoading2(false);
        }
    };

    // 关闭编辑弹出框
    const handleCloseEditModal = () => {
        setShowEditModal(false);
        setCurrentEditId(null);
        setEditFormData({
            warehouse: '',
            team: '',
            inventoryCode: '',
            states: '启用'
        });
    };

    // 处理编辑表单输入变化
    const handleEditFormChange = (field: keyof AddFormData, value: string) => {
        console.log('编辑表单变化:', field, value);
        setEditFormData(prev => {
            const newData = {
                ...prev,
                [field]: value
            };
            console.log('更新后的表单数据:', newData);
            return newData;
        });
    };

    // 保存编辑数据
    const handleUpdate = async () => {
        if (!editFormData.warehouse.trim() || !editFormData.team.trim()) {
            alert('请填写完整的仓库和团队信息');
            return;
        }

        if (!currentEditId) {
            alert('编辑ID丢失，请重新打开编辑窗口');
            return;
        }

        try {
            setSaving(true);
            console.log('发送更新请求，数据:', {
                Id: currentEditId,
                Warehouse: editFormData.warehouse.trim(),
                Team: editFormData.team.trim(),
                InventoryCode: editFormData.inventoryCode,
                States: editFormData.states
            });
            
            const response = await fetch('http://localhost:5233/api/PendingOrders/UpdatePendingOrders', {
                method: 'POST', // 尝试使用POST方法
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    Id: currentEditId,
                    Warehouse: editFormData.warehouse.trim(),
                    Team: editFormData.team.trim(),
                    InventoryCode: editFormData.inventoryCode,
                    States: editFormData.states
                })
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();
            console.log('更新成功:', result);
            
            // 关闭弹出框并重新加载数据
            handleCloseEditModal();
            fetchPendingOrders(queryParams);
            alert('更新成功！');
        } catch (err) {
            console.error('更新失败:', err);
            alert('更新失败: ' + (err instanceof Error ? err.message : '未知错误'));
        } finally {
            setSaving(false);
        }
    };

    const handleDelete = async (id: number) => {
        // 弹出确认框
        if (!window.confirm('确定要删除这条盘点订单吗？')) {
            return;
        }

        try {
            const response = await fetch('http://localhost:5233/api/PendingOrders/DeletePendingOrders', {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ id: id })
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();
            console.log('删除成功:', result);
            
            // 重新加载数据
            fetchPendingOrders(queryParams);
            alert('删除成功！');
        } catch (err) {
            console.error('删除失败:', err);
            alert('删除失败: ' + (err instanceof Error ? err.message : '未知错误'));
        }
    };

    const getStatusBadge = (status: string) => {
        const statusClass = status === "待确认" ? styles.statusPending : styles.statusInProgress;
        return <span className={`${styles.statusBadge} ${statusClass}`}>{status}</span>;
    };

    // 处理全选/取消全选
    const handleSelectAll = (checked: boolean) => {
        if (checked) {
            setSelectedItems(pendingorderList.map(item => item.id));
        } else {
            setSelectedItems([]);
        }
    };

    // 处理单个项目的选择
    const handleSelectItem = (id: number, checked: boolean) => {
        if (checked) {
            setSelectedItems(prev => [...prev, id]);
        } else {
            setSelectedItems(prev => prev.filter(itemId => itemId !== id));
        }
    };

    // 批量删除
    const handleBatchDelete = async () => {
        if (selectedItems.length === 0) {
            alert('请至少选择一条记录');
            return;
        }

        // 弹出确认框
        if (!window.confirm(`确定要删除选中的 ${selectedItems.length} 条记录吗？`)) {
            return;
        }

        try {
            const response = await fetch('http://localhost:5233/api/PendingOrders/DeletePendingOrdersAnage', {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                    'X-HTTP-Method-Override': 'DELETE'
                },
                body: JSON.stringify({
                    Ids: selectedItems
                })
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();
            console.log('批量删除成功:', result);
            
            // 清空选中项
            setSelectedItems([]);
            // 重新加载数据
            fetchPendingOrders(queryParams);
            alert('批量删除成功！');
        } catch (err) {
            console.error('批量删除失败:', err);
            alert('批量删除失败: ' + (err instanceof Error ? err.message : '未知错误'));
        }
    };

    // 加载状态
    if (loading) {
        return (
            <div className={styles.container}>
                <h3 className={styles.title}>待盘点订单</h3>
                <div className={styles.emptyState}>
                    <p>正在加载数据...</p>
                </div>
            </div>
        );
    }

    // 错误状态
    if (error) {
        return (
            <div className={styles.container}>
                <h3 className={styles.title}>待盘点订单</h3>
                <div className={styles.emptyState}>
                    <p>加载失败: {error}</p>
                    <button 
                        onClick={() => fetchPendingOrders()}
                        style={{
                            marginTop: '10px',
                            padding: '8px 16px',
                            backgroundColor: '#4CAF50',
                            color: 'white',
                            border: 'none',
                            borderRadius: '4px',
                            cursor: 'pointer'
                        }}
                    >
                        重新加载
                    </button>
                </div>
            </div>
        );
    }

    return (
        <div className={styles.container}>
            <h3 className={styles.title}>待盘点订单</h3>
            
            {/* 查询表单 */}
            <div className={styles.queryForm}>
                <div className={styles.queryRow}>
                    <div className={styles.queryField}>
                        <label className={styles.queryLabel}>仓库:</label>
                        <input
                            type="text"
                            className={styles.queryInput}
                            placeholder="请输入仓库名称"
                            value={queryParams.warehouse}
                            onChange={(e) => handleInputChange('warehouse', e.target.value)}
                        />
                    </div>
                    <div className={styles.queryField}>
                        <label className={styles.queryLabel}>团队:</label>
                        <input
                            type="text"
                            className={styles.queryInput}
                            placeholder="请输入团队名称"
                            value={queryParams.team}
                            onChange={(e) => handleInputChange('team', e.target.value)}
                        />
                    </div>
                    <div className={styles.queryField}>
                        <label className={styles.queryLabel}>盘点单号:</label>
                        <input
                            type="text"
                            className={styles.queryInput}
                            placeholder="请输入盘点单号"
                            value={queryParams.inventoryCode}
                            onChange={(e) => handleInputChange('inventoryCode', e.target.value)}
                        />
                    </div>
                    <div className={styles.queryButtons}>
                        <button 
                            className={`${styles.queryButton} ${styles.searchButton}`}
                            onClick={handleSearch}
                        >
                            查询
                        </button>
                        <button 
                            className={`${styles.queryButton} ${styles.clearButton}`}
                            onClick={handleClear}
                        >
                            清空
                        </button>
                        <button 
                            className={`${styles.queryButton} ${styles.addButton}`}
                            onClick={handleAdd}
                        >
                            新增
                        </button>
                        <button 
                            className={`${styles.queryButton} ${styles.deleteButton}`}
                            onClick={handleBatchDelete}
                            disabled={selectedItems.length === 0}
                        >
                            批量删除
                        </button>
                    </div>
                </div>
            </div>

            {!Array.isArray(pendingorderList) || pendingorderList.length === 0 ? (
                <div className={styles.emptyState}>
                    <p>{!Array.isArray(pendingorderList) ? '数据格式错误' : '暂无待盘点订单'}</p>
                </div>
            ) : (
                <div className={styles.tableContainer}>
                    <table className={styles.table}>
                        <thead>
                            <tr>
                                <th>
                                    <input
                                        type="checkbox"
                                        checked={selectedItems.length === pendingorderList.length}
                                        onChange={(e) => handleSelectAll(e.target.checked)}
                                    />
                                </th>
                                <th>盘点ID</th>
                                <th>团队名称</th>
                                <th>仓库名称</th>
                                <th>盘点单号</th>
                                <th>盘点状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {pendingorderList.map((product) => (
                                <tr key={product.id}>
                                    <td>
                                        <input
                                            type="checkbox"
                                            checked={selectedItems.includes(product.id)}
                                            onChange={(e) => handleSelectItem(product.id, e.target.checked)}
                                        />
                                    </td>
                                    <td>{product.id}</td>
                                    <td>{product.team}</td>
                                    <td>{product.warehouse}</td>
                                    <td>{product.inventoryCode}</td>
                                    <td>{getStatusBadge(product.states)}</td>
                                    <td className={styles.operationCell}>
                                        <button 
                                            className={`${styles.operationButton} ${styles.editButton}`}
                                            onClick={() => handleEdit(product.id)}
                                            title="编辑订单"
                                        >
                                            编辑
                                        </button>
                                        <button 
                                            className={`${styles.operationButton} ${styles.deleteButton}`}
                                            onClick={() => handleDelete(product.id)}
                                            title="删除订单"
                                        >
                                            删除
                                        </button>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            )}

            {/* 新增弹出框 */}
            {showModal && (
                <div className={styles.modalOverlay}>
                    <div className={styles.modal}>
                        <div className={styles.modalHeader}>
                            <h4>新增待盘点订单</h4>
                            <button 
                                className={styles.closeButton}
                                onClick={handleCloseModal}
                            >
                                ×
                            </button>
                        </div>
                        <div className={styles.modalBody}>
                            <div className={styles.formField}>
                                <label className={styles.formLabel}>仓库 <span className={styles.required}>*</span>:</label>
                                <select
                                    className={styles.formInput}
                                    value={formData.warehouse}
                                    onChange={(e) => handleFormChange('warehouse', e.target.value)}
                                >
                                    <option value="">请选择仓库</option>
                                    {warehouseOptions.map(option => (
                                        <option key={option.value} value={option.value}>
                                            {option.label}
                                        </option>
                                    ))}
                                </select>
                            </div>
                            <div className={styles.formField}>
                                <label className={styles.formLabel}>团队 <span className={styles.required}>*</span>:</label>
                                <select
                                    className={styles.formInput}
                                    value={formData.team}
                                    onChange={(e) => handleFormChange('team', e.target.value)}
                                >
                                    <option value="">请选择团队</option>
                                    {teamOptions.map(option => (
                                        <option key={option.value} value={option.value}>
                                            {option.label}
                                        </option>
                                    ))}
                                </select>
                            </div>
                            <div className={styles.formField}>
                                <label className={styles.formLabel}>盘点单号:</label>
                                <input
                                    type="text"
                                    className={styles.formInput}
                                    value={formData.inventoryCode}
                                    readOnly
                                    style={{ backgroundColor: '#f5f5f5', cursor: 'not-allowed' }}
                                />
                            </div>
                            <div className={styles.formField}>
                                <label className={styles.formLabel}>状态:</label>
                                <div className={styles.radioGroup}>
                                    <label className={styles.radioLabel}>
                                        <input
                                            type="radio"
                                            name="states"
                                            value="启用"
                                            checked={formData.states === '启用'}
                                            onChange={(e) => handleFormChange('states', e.target.value)}
                                        />
                                        启用
                                    </label>
                                    <label className={styles.radioLabel}>
                                        <input
                                            type="radio"
                                            name="states"
                                            value="禁用"
                                            checked={formData.states === '禁用'}
                                            onChange={(e) => handleFormChange('states', e.target.value)}
                                        />
                                        禁用
                                    </label>
                                </div>
                            </div>
                        </div>
                        <div className={styles.modalFooter}>
                            <button 
                                className={`${styles.modalButton} ${styles.cancelButton}`}
                                onClick={handleCloseModal}
                            >
                                取消
                            </button>
                            <button 
                                className={`${styles.modalButton} ${styles.saveButton}`}
                                onClick={handleSave}
                                disabled={saving}
                            >
                                {saving ? '保存中...' : '保存'}
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* 编辑弹出框 */}
            {showEditModal && (
                <div className={styles.modalOverlay}>
                    <div className={styles.modal}>
                        <div className={styles.modalHeader}>
                            <h4>编辑待盘点订单</h4>
                            <button 
                                className={styles.closeButton}
                                onClick={handleCloseEditModal}
                            >
                                ×
                            </button>
                        </div>
                                                 <div className={styles.modalBody}>
                             {loading2 ? (
                                 <div style={{ textAlign: 'center', padding: '20px' }}>
                                     <p>正在加载数据...</p>
                                 </div>
                             ) : (
                                 <>
                                     <div className={styles.formField}>
                                         <label className={styles.formLabel}>仓库 <span className={styles.required}>*</span>:</label>
                                         <select
                                             className={styles.formInput}
                                             value={editFormData.warehouse || ''}
                                             onChange={(e) => handleEditFormChange('warehouse', e.target.value)}
                                         >
                                             <option value="">请选择仓库</option>
                                             {warehouseOptions.map(option => (
                                                 <option key={option.value} value={option.value}>
                                                     {option.label}
                                                 </option>
                                             ))}
                                         </select>
                                     </div>
                                     <div className={styles.formField}>
                                         <label className={styles.formLabel}>团队 <span className={styles.required}>*</span>:</label>
                                         <select
                                             className={styles.formInput}
                                             value={editFormData.team || ''}
                                             onChange={(e) => handleEditFormChange('team', e.target.value)}
                                         >
                                             <option value="">请选择团队</option>
                                             {teamOptions.map(option => (
                                                 <option key={option.value} value={option.value}>
                                                     {option.label}
                                                 </option>
                                             ))}
                                         </select>
                                     </div>
                                     <div className={styles.formField}>
                                         <label className={styles.formLabel}>盘点单号:</label>
                                         <input
                                             type="text"
                                             className={styles.formInput}
                                             value={editFormData.inventoryCode}
                                             readOnly
                                             style={{ backgroundColor: '#f5f5f5', cursor: 'not-allowed' }}
                                         />
                                     </div>
                                     <div className={styles.formField}>
                                         <label className={styles.formLabel}>状态:</label>
                                         <div className={styles.radioGroup}>
                                             <label className={styles.radioLabel}>
                                                 <input
                                                     type="radio"
                                                     name="editStates"
                                                     value="启用"
                                                     checked={editFormData.states === '启用'}
                                                     onChange={(e) => handleEditFormChange('states', e.target.value)}
                                                 />
                                                 启用
                                             </label>
                                             <label className={styles.radioLabel}>
                                                 <input
                                                     type="radio"
                                                     name="editStates"
                                                     value="禁用"
                                                     checked={editFormData.states === '禁用'}
                                                     onChange={(e) => handleEditFormChange('states', e.target.value)}
                                                 />
                                                 禁用
                                             </label>
                                         </div>
                                     </div>
                                 </>
                             )}
                         </div>
                        <div className={styles.modalFooter}>
                            <button 
                                className={`${styles.modalButton} ${styles.cancelButton}`}
                                onClick={handleCloseEditModal}
                            >
                                取消
                            </button>
                            <button 
                                className={`${styles.modalButton} ${styles.saveButton}`}
                                onClick={handleUpdate}
                                disabled={saving}
                            >
                                {saving ? '保存中...' : '保存'}
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}

export default PendingOrdersQuery;